﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using shop.Properties;
using shop.Model;
using CommonTools;
using CommonTools.Controls;
using shop.Bll;
using System.Threading.Tasks;
using Common;

namespace shop
{
    public partial class Account : GtMetroForm
    {

        private bool _initing = false;

        public Account(SoftOwnerModel owner)
            :this()
        {
            this.label2.Text = owner.TitleOnLogin;
            this.linkGuantong.Text = owner.Developer;
        }

        private Account()
        {
            InitializeComponent();

            Lab_ver.Text = "版本:"+ myApp.MyVersion.ToString();

            this.box_user.Text = IniSet.ReadIniData("user", "name", "");
            this.box_server.Text = myApp.Server; //服务器地址

            this .StartPosition = FormStartPosition.CenterScreen;

            if (myApp.Owner != null)
            {
                this.label2.Text = myApp.Owner.CompanyName;
                this.linkGuantong.Text = myApp.Owner.Developer;
            }

        }
 

        private void Account_Load(object sender, EventArgs e)
        {
            if (this.box_user.Text != "")
            {
                this.ActiveControl = this.box_pwd;
            }
        }

        private void btn_winclose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_winmin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private async void btn_login_Click(object sender, EventArgs e)
        {
            this.labMessage.Text = string.Empty;
            if (this.box_server.Text.Trim() == "")
            {
                MessageTip.ShowError(this, Resources.msg_serverBlank);
                this.labMessage.Text = Resources.msg_serverBlank;
                return;
            }

            var t = this.btn_login.Text;
            this.btn_login.Text = "正在登录...";
            this.btn_login.Enabled = false;
            this.pictureBox1.Image = Properties.Resources.loading4;

            //如果后台还在初始化, 等待
            while(_initing)
            {
                await Task.Delay(50);
            }

            try
            {
                //检查地址
                if (TestServer(this.box_server.Text.Trim()) == false)
                {
                    this.btn_login.Text = t;
                    MessageTip.ShowError(this, "服务器地址不正确, 或服务未开启!");
                    this.labMessage.Text = "服务器地址不正确, 或服务未开启!";
                    return;
                }

    
                if (this.box_user.Text.Trim() == "")
                {
                    this.btn_login.Text = t;
                    MessageTip.ShowError(this, Resources.userBlank);
                    this.labMessage.Text = Resources.userBlank;
                    return;
                }

                JUser user = new JUser
                {
                    Name = this.box_user.Text.Trim()
                };


                //更新服务器地址
                if (myApp.Server != this.box_server.Text.Trim())
                {
                    myApp.Server = this.box_server.Text.Trim();
                    DB.FSql = null; //重置数据库
                }


                if (DB.FSql == null)
                {
                    var bl = await Task.Run(() => DB.Init(myApp.Server, true));
                    if (!bl)
                    {
                        MessageTip.ShowError(this, "没有找到数据库, 不能继续!");
                        this.labMessage.Text = "没有找到数据库, 不能继续!";
                        //MessageBox.Show("没有找到数据库, 不能继续!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }


                var res = await Task.Run(() => new UserBll().TryLogin(user, this.box_pwd.Text));
                if (res)
                {
                    this.btn_login.Text = t;

                    IniSet.WriteIniData("user", "name", this.box_user.Text);

                    //更新服务器地址
                    myApp.Server = this.box_server.Text.Trim();
                    myApp.StartJobMessage();

                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
                else
                {
                    this.btn_login.Text = t;
                    MessageTip.ShowError(this, Resources.passwordWrong,-1, true);
                    this.labMessage.Text = Resources.passwordWrong;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.btn_login.Text = t;
                this.btn_login.Enabled = true; ;
                var resources = new System.ComponentModel.ComponentResourceManager(typeof(Account));
                this.pictureBox1.Image = (Image)(resources.GetObject("pictureBox1.Image"));
            }


        }




        private void btn_setting_Click(object sender, EventArgs e)
        {

        }



        /// <summary> 检查服务器连接 </summary>
        private bool TestServer(string serv)
        {
            serv = serv.Trim();

            if (string.IsNullOrEmpty(serv))
            {
                //MessageBox.Show("服务器地址不能为空");
                return false;
            }

            //string con = $"server={serv};database=master;uid=sa;pwd=Shijian2017;timeout=8";  //超时3秒

            try
            {
                //SqlHelper.ExecuteDataset(con, CommandType.Text, "select getdate()");
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        private async void Account_Shown(object sender, EventArgs e)
        {
            //初始化
            if (DB.FSql == null && string.IsNullOrEmpty(myApp.Server) == false)
            {
                _initing = true;

                try
                {
                    await Task.Run(() => myApp.Init());
                    await Task.Run(() => DB.Init(myApp.Server, true));
                }
                catch (Exception)
                {
                    //throw;
                }
                finally
                {
                    _initing = false ;
                }
            }

        }
    }
}